package com.xckj.cycling.framework.net;

import androidx.annotation.NonNull;

import com.xckj.cycling.bean.BaseBean;
import com.xckj.cycling.global.Constant;

import java.io.IOException;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * @Author: ChenYao
 * @Describe: 请求工具
 * @Date: 2023/2/26 19:10
 */
public class RequestUtils {
    public static <T> T syncRequest(Call<BaseBean<T>> call) throws IOException, HttpException {
        Call<BaseBean<T>> newCall = call.clone();
        Response<BaseBean<T>> response = call.execute();
        if (response.isSuccessful()) {
            BaseBean<T> baseBean = response.body();
            if (Constant.SUCCESS_CODE == Objects.requireNonNull(baseBean).code) {
                return baseBean.data;
            }
        } else {
            throw new HttpException(response);
        }
        return null;
    }

    public static <T> void asyncRequest(Call<BaseBean<T>> call, AsyncCallback<T> callback) {
        Call<BaseBean<T>> newCall = call.clone();
        call.enqueue(new Callback<BaseBean<T>>() {
            @Override
            public void onResponse(@NonNull Call<BaseBean<T>> call, @NonNull Response<BaseBean<T>> response) {
                if (response.isSuccessful()) {
                    BaseBean<T> baseBean = response.body();
                    if (Constant.SUCCESS_CODE == Objects.requireNonNull(baseBean).code) {
                        callback.requestSuccess(baseBean.data);
                    } else {
                        callback.requestErr(baseBean.code, baseBean.msg);
                    }
                } else {
                    String errMsg = "请求失败";
                    try {
                        errMsg = Objects.requireNonNull(response.errorBody()).string();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    callback.requestErr(response.code(), errMsg);
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseBean<T>> call, @NonNull Throwable t) {
                t.printStackTrace();
            }
        });
    }

    public interface AsyncCallback<T> {
        /**
         * 请求成功
         *
         * @param t t
         */
        void requestSuccess(T t);

        /**
         * 请求失败
         *
         * @param code 错误码
         * @param msg  错误信息
         */
        void requestErr(int code, String msg);
    }
}
